package com.example.managemyself.util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 媒体文件管理器
 * 处理文件创建、保存和管理
 */
public class MediaFileManager {
    
    private static final String TAG = "MediaFileManager";
    private static final String FILE_PROVIDER_AUTHORITY = "com.example.managemyself.fileprovider";
    
    private Context context;
    
    public MediaFileManager(Context context) {
        this.context = context.getApplicationContext();
    }
    
    /**
     * 创建图片文件
     */
    public File createImageFile() {
        try {
            // 创建时间戳文件名
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            String imageFileName = "DIARY_IMG_" + timeStamp + "_";
            
            // 获取应用专用目录
            File storageDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "DiaryImages");
            if (!storageDir.exists()) {
                storageDir.mkdirs();
            }
            
            File imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
            
            Log.d(TAG, "创建图片文件: " + imageFile.getAbsolutePath());
            return imageFile;
            
        } catch (IOException e) {
            Log.e(TAG, "创建图片文件失败", e);
            return null;
        }
    }
    
    /**
     * 创建视频文件
     */
    public File createVideoFile() {
        try {
            // 创建时间戳文件名
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            String videoFileName = "DIARY_VID_" + timeStamp + "_";
            
            // 获取应用专用目录
            File storageDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_MOVIES), "DiaryVideos");
            if (!storageDir.exists()) {
                storageDir.mkdirs();
            }
            
            File videoFile = File.createTempFile(videoFileName, ".mp4", storageDir);
            
            Log.d(TAG, "创建视频文件: " + videoFile.getAbsolutePath());
            return videoFile;
            
        } catch (IOException e) {
            Log.e(TAG, "创建视频文件失败", e);
            return null;
        }
    }
    
    /**
     * 复制外部文件到应用目录
     */
    public File copyFileToAppDirectory(Uri sourceUri, String fileType) {
        try {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            String fileName = "DIARY_" + fileType.toUpperCase() + "_" + timeStamp;
            
            // 根据文件类型确定目录和扩展名
            File targetDir;
            String extension;
            
            switch (fileType.toLowerCase()) {
                case "image":
                    targetDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "DiaryImages");
                    extension = ".jpg";
                    break;
                case "video":
                    targetDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_MOVIES), "DiaryVideos");
                    extension = ".mp4";
                    break;
                case "audio":
                    targetDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_MUSIC), "DiaryAudio");
                    extension = ".mp3";
                    break;
                case "document":
                    targetDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), "DiaryDocs");
                    extension = ".pdf";
                    break;
                default:
                    targetDir = new File(context.getExternalFilesDir(null), "DiaryFiles");
                    extension = "";
            }
            
            if (!targetDir.exists()) {
                targetDir.mkdirs();
            }
            
            File targetFile = new File(targetDir, fileName + extension);
            
            // 复制文件
            try (java.io.InputStream inputStream = context.getContentResolver().openInputStream(sourceUri);
                 java.io.FileOutputStream outputStream = new java.io.FileOutputStream(targetFile)) {
                
                byte[] buffer = new byte[4096];
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
            }
            
            Log.d(TAG, "文件复制成功: " + targetFile.getAbsolutePath());
            return targetFile;
            
        } catch (Exception e) {
            Log.e(TAG, "复制文件失败", e);
            return null;
        }
    }
    
    /**
     * 获取文件的Uri
     */
    public Uri getFileUri(File file) {
        return FileProvider.getUriForFile(context, FILE_PROVIDER_AUTHORITY, file);
    }
    
    /**
     * 检查文件是否存在
     */
    public boolean fileExists(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            return false;
        }
        
        File file = new File(filePath);
        return file.exists();
    }
    
    /**
     * 删除文件
     */
    public boolean deleteFile(String filePath) {
        try {
            File file = new File(filePath);
            if (file.exists()) {
                boolean deleted = file.delete();
                Log.d(TAG, "删除文件: " + filePath + ", 结果: " + deleted);
                return deleted;
            }
            return true;
        } catch (Exception e) {
            Log.e(TAG, "删除文件失败: " + filePath, e);
            return false;
        }
    }
    
    /**
     * 获取文件大小
     */
    public long getFileSize(String filePath) {
        try {
            File file = new File(filePath);
            return file.exists() ? file.length() : 0;
        } catch (Exception e) {
            Log.e(TAG, "获取文件大小失败: " + filePath, e);
            return 0;
        }
    }
} 